package com.button.boot.active.comsumer;

import java.time.LocalDateTime;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import com.button.boot.active.model.User;

import net.sf.json.JSONObject;

@Component
public class Consumer1 {
    private static final Logger log = LoggerFactory.getLogger(Consumer1.class);
    
    @JmsListener(destination = "queue_string",containerFactory = "queueListenerFactory")
    public void receiveQueue(String text) {
        log.info("consumer1收到queue_string信息:{}", text);
    }

    @JmsListener(destination = "queue_user",containerFactory = "queueListenerFactory")
    public void receiveQueue(User user) {
        log.info("consumer1收到queue_user信息:{}", JSONObject.fromObject(user));
    }

    @JmsListener(destination = "queue_return",containerFactory = "queueListenerFactory")
    @SendTo("queue_return") //该注解的意思是将return回的值，再发送的"queue_return"队列中
    public String receive2WayQueue(String text) {
        log.info("consumer1收到queue_return的信息:{}",text);
        return "queue_return最后return的内容";
    }
    
    //接收queue_return的内容
    @JmsListener(destination = "queue_return", containerFactory = "queueListenerFactory")
    public void receiveReturnQueue(String text) {
        log.info("consumer1收到queue_return信息:{}",text);
    }

    @SuppressWarnings("unused")
    @JmsListener(destination = "queue_ack", containerFactory = "queueListenerACKFactory")
    public void receiveQueue(TextMessage message, Session session) throws JMSException {
        log.info("consumer1收到queue_string信息:{}", message.getText());
        try {
            int a = 1 / 0;
            message.acknowledge();  //消息确认
        } catch (Exception e) {
            log.error("消费消息是出现异常,消息重发. e={}", e);
            session.recover();  //消息重发，默认每秒重发1次，一共重发6次
        }
    }

    @JmsListener(destination = "topic_string",containerFactory = "topicListenerFactory")
    public void receiveTopic(String text) {
        log.info("consumer1收到topic_string信息:{}", text);
    }

    @JmsListener(destination = "topic_user",containerFactory = "topicListenerFactory")
    public void receiveTopic(User user) {
        log.info("consumer1收到topic_user信息:{}", JSONObject.fromObject(user));
    }

    @JmsListener(destination = "topic_delay",containerFactory = "topicListenerFactory")
    public void receiveDelayTopic(String text) {
        log.info("consumer1收到topic_delay_string延时信息:{},接收时间:{}", text, LocalDateTime.now());
    }
}
